package data.admin;

import dao.SQLiteConnection;
import gui.admin.AddWin;
import javax.swing.*;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;


public class Add extends AddWin {

    SQLiteConnection Connection = new SQLiteConnection();

    Add() {
        getB1().addActionListener(e -> {
            //获取文本框的内容
            String ISBN = getT1().getText();
            String bookname = getT2().getText();
            String booktype = getT3().getText();
            String publisher = getT4().getText();
            String author = getT5().getText();
            String number = getT6().getText();
            //空判断
            if (ISBN == null || ISBN.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "ISBN不能为空！");
            } else if (bookname == null || bookname.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "书名不能为空！");
            } else if (booktype == null || booktype.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "分类不能为空！");
            } else if (publisher == null || publisher.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "出版社不能为空！");
            } else if (author == null || author.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "作者不能为空！");
            } else if (number == null || number.trim().isEmpty()) {
                JOptionPane.showMessageDialog(this, "馆藏不能为空！");
            }
            //添加图书
            else {
                Connection.Connect_SQLite();
                try {
                    Connection conn = Connection.getConnection();
                    Statement stmt = conn.createStatement();
                    String sql1 = "INSERT INTO Book (ISBN, bookname, booktype, publisher, author, number)" +
                            " VALUES ('" + ISBN + "','" + bookname + "', '" + booktype + "', '" + publisher + "', '" + author + "', " + number + ")";
                    int rowsAdd=stmt.executeUpdate(sql1);
                    if(rowsAdd>0){
                        System.out.println("数据已成功写入数据库");
                        JOptionPane.showMessageDialog(this,"添加成功");
                        dispose();
                    }
                } catch (SQLException ex) {
                    System.out.println("写入数据库时发生错误：" + ex.getMessage());
                }
            }
        });
        getB2().addActionListener(e-> dispose());
    }

}
